package com.zyh.cxf;



import com.zyh.dao.KeyMapper;
import com.zyh.pojo.*;

import com.zyh.util.XstreamKit;
import com.zyh.util.safeutil.DESedeUtil;
import com.zyh.util.safeutil.SM2Utils;
import com.zyh.util.safeutil.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Map;


/**
 * @author caoyoufang
 * @date 2020-12-09
 * 获取sm4key
 */
@Component
public class GetPublicKeyImpl implements GetPublicKey {


    @Autowired
    private KeyMapper keyMapper;
    public static GetPublicKeyImpl getPublicKeyImpl;

    @PostConstruct
    public void init() {

        getPublicKeyImpl = this;
        getPublicKeyImpl.keyMapper = this.keyMapper;
    }


    @Override
    public String getPublicKeyInfo(String xmlData) {

//         获取秘钥
        String key = null;
        try {
            key = DESedeUtil.generateKey();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map keyPair = SM2Utils.generateKeyPair();

        String publicKey=keyPair.get(SM2Utils.PUBLIC_KEY).toString();
        String privateKey=keyPair.get(SM2Utils.PRIVATE_KEY).toString();
        System.err.println("加密：");



        String cipherText = null;
        try {
            cipherText = SM2Utils.encrypt(Util.hexToByte(publicKey), key.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("密文：" + cipherText);


        updateGetKey();
        YyzlKey yyzlKey=new YyzlKey();
        yyzlKey.setPublicKey(cipherText);
        yyzlKey.setPrivateKey(privateKey);
        addGetKey(yyzlKey);
        OutKeyMessage ybxml = new OutKeyMessage();
        OutHeadPojo ybhead = new OutHeadPojo();
        ybhead.setIBSJnlNo("1");//网银流水号
        ybhead.setIBSReturnCode("000000");//网银返回码
        ybhead.setIBSReturnMsg("查询成功");//网银返回信息
        ybhead.setSerialNo("1");//交易流水号
        ybxml.setHead(ybhead);
        OutKeyPojo ybbody = new OutKeyPojo();
        ybbody.setKey(key);
        ybxml.setBody(ybbody);
    //返回
       String  responseToYBxml = XstreamKit.vo2Xml(ybxml);
        return responseToYBxml;
    }


    public static void addGetKey(YyzlKey yyzlKey) {

        getPublicKeyImpl.keyMapper.addKey(yyzlKey);
    }
    public static void updateGetKey() {

        getPublicKeyImpl.keyMapper.updateKey();
    }
}
